﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Services
{
    public static class ConvertListAndTable
    {
        #region List和DataTable的互相转换
        /// <summary>
        /// DataTable to List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            if (dt == null)
            {
                return null;
            }
            System.Data.DataColumnCollection columns = dt.Columns;
            int iColumnCount = columns.Count;
            int i;
            int j;
            T entity = new T();
            Type elementType;
            elementType = entity.GetType();
            System.Reflection.PropertyInfo[] publicProperties = elementType.GetProperties();
            List<T> result = new List<T>();
            if (publicProperties.Length == iColumnCount)
            {
                foreach (DataRow currentRow in dt.Rows)
                {
                    for (i = 0; i < iColumnCount; i++)
                    {
                        for (j = 0; j < publicProperties.Length; j++)
                        {
                            if (columns[i].ColumnName == publicProperties[j].Name)
                            {
                                publicProperties[j].SetValue(entity, HackType(currentRow[i], publicProperties[j].PropertyType), null);
                            }
                        }
                    }
                    result.Add(entity);
                    entity = new T();
                }
            }
            else
            {
                result = null;
            }
            return result;
        }

        /// <summary>
        /// List to DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
            //生成DataTable的structure
            //生产代码中，应将生成的DataTable结构Cache起来，此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }

        //这个类对可空类型进行判断转换，要不然会报错   
        private static object HackType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                    return null;

                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            return Convert.ChangeType(value, conversionType);
        }
        #endregion
    }
}
